const initialState = {
  userList: [] as ChannelItem[],
  allList: [] as ChannelItem[],
  currentId: 0,
};

export type ActionType =
  | { type: 'channel/saveUserList'; payload: ChannelItem[] }
  | { type: 'channel/saveAllList'; payload: ChannelItem[] }
  | { type: 'channel/updateUserList'; payload: ChannelItem }
  | { type: 'channel/delUserList'; payload: number }
  | { type: 'channel/setCurrentId'; payload: number };

function channelReducer(state = initialState, action: ActionType): typeof initialState {
  switch (action.type) {
    case 'channel/saveUserList':
      return {
        ...state,
        userList: action.payload,
      };
    case 'channel/saveAllList':
      return {
        ...state,
        allList: action.payload,
      };
    case 'channel/updateUserList':
      return {
        ...state,
        userList: [...state.userList, action.payload].sort(
          (aItem, bItem) => aItem.id - bItem.id
        ),
      };

    case 'channel/delUserList':
      return {
        ...state,
        userList: state.userList.filter((item) => item.id !== action.payload),
      };

    case 'channel/setCurrentId':
      return {
        ...state,
        currentId: action.payload,
      };

    default:
      return state;
  }
}

export default channelReducer;

export interface ChannelItem {
  id: number;
  name: string;
}
